package com.dd.admin.common.mybatisPlus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.dd.admin.common.security.SecurityUtil;
import com.dd.admin.common.security.model.JwtUser;
import com.dd.admin.common.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {

        log.info("start insert fill ....");
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date()); // 起始版本 3.3.0(推荐使用)

        try {
            JwtUser jwtUser = SecurityUtil.getLoginUser();

            String deptId = String.valueOf(getFieldValByName("deptId",metaObject));
            if(StringUtil.isEmpty(deptId)){
                this.strictInsertFill(metaObject, "deptId", String.class, jwtUser.getDeptId()); // 起始版本 3.3.0(推荐使用)
            }

            String deptName = String.valueOf(getFieldValByName("deptName",metaObject));
            if(StringUtil.isEmpty(deptName)){
                this.strictInsertFill(metaObject, "deptName", String.class, jwtUser.getDeptName()); // 起始版本 3.3.0(推荐使用)
            }

            String createId = String.valueOf(getFieldValByName("createId",metaObject));
            if(StringUtil.isEmpty(createId)){
                this.strictInsertFill(metaObject, "createId", String.class, jwtUser.getUserId()); // 起始版本 3.3.0(推荐使用)
            }

            String createName = String.valueOf(getFieldValByName("createName",metaObject));
            if(StringUtil.isEmpty(createId)){
                this.strictInsertFill(metaObject, "createName", String.class, jwtUser.getUsername()); // 起始版本 3.3.0(推荐使用)
            }
        }catch (Exception exception){

        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        this.strictUpdateFill(metaObject, "updateTime",Date.class, new Date()); // 起始版本 3.3.0(推荐)

        JwtUser jwtUser = SecurityUtil.getLoginUser();

        String updateId = String.valueOf(getFieldValByName("updateId",metaObject));
        if(StringUtil.isEmpty(updateId)){
            this.strictUpdateFill(metaObject, "updateId", String.class, jwtUser.getUserId()); // 起始版本 3.3.0(推荐使用)
        }

        String updateName = String.valueOf(getFieldValByName("updateName",metaObject));
        if(StringUtil.isEmpty(updateName)){
            this.strictUpdateFill(metaObject, "updateName", String.class, jwtUser.getUsername()); // 起始版本 3.3.0(推荐使用)
        }
    }
}
